<?php

/**
 * uniBoard Sessions Tracker
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date: 2010-09-20 21:23:27 +0000 (Mon, 20 Sep 2010) $
 * $Revision: 64 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class class_sessions_tracker{
	
	/**
	 * Main class pointer
	 *
	 * @var object
	 */
	
	private $appCore		= NULL;
	
	/**
	 * Session Data
	 *
	 * @var array
	 */
	
	private $sessions		= array();
	
	// ------------------------------------------------------------------------

	/**
	 * Initialise Helper
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Store appCore pointer
		$this -> appCore = $appCore;

		// Load Session Data?
		if ( $appCore -> conf['sessions_tracker_refresh'] > 0)
		{
			$this -> sessions = class_cache::loadCache('sessions');	
		}
		
		// Build cache or load users?
		if ( $appCore -> conf['sessions_tracker_refresh'] == 0 || ($appCore -> conf['sessions_tracker_refresh'] > 0 && class_cache::$load_error))
		{
			// Empty sessions array
			$this -> sessions = array();
			
			// Select Sessions
			$appCore -> db -> query('SELECT user_id, session_last_active, session_hidden
			FROM ' . DB_PREFIX . 'sessions
			WHERE user_id > \'0\' AND session_last_active >= \'' . ($this -> appCore -> time - ($this -> appCore -> conf['session_activity_span'] * 60)) . '\'');
			
			// Put them into array
			while ( $user_result = $appCore -> db -> fetch_array())
			{
				// Put user into array
				if ( !isset($this -> sessions[$user_result[0]]) || $this -> sessions[$user_result[0]][0] < $user_result[1] || $this -> sessions[$user_result[0]][1] && !$user_result[2])
				{
					$this -> sessions[$user_result[0]] = array($user_result[1], $user_result[2]);
				}
			}
			
			// Save cache
			if ($appCore -> conf['sessions_tracker_refresh'] > 0)
			{
				class_cache::saveCache('sessions', $this -> sessions, $appCore -> conf['sessions_tracker_refresh'] * 60);
			}
		}
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Returns user status
	 *
	 * @param integer $user_id
	 * @return bool
	 */
	
	function checkStatus( $user_id){

		// User is us?
		if ($user_id == $this -> appCore -> user['id'])
		{
			return true;			
		}
		else if ( isset($this -> sessions[$user_id]) && $this -> sessions[$user_id][0] >= ($this -> appCore -> time - ($appCore -> conf['sessions_tracker_refresh'] * 60)))
		{
			// Check if hidden status is allrite
			return (!$this -> sessions[$user_id][1] || ($this -> sessions[$user_id][1] && $this -> appCore -> user_acl['can_see_hidden']));
		}
		
		// Return false as user is offline
		return false;
	}
	
}